package saucaca.CustomView;

import java.util.ArrayList;

import org.json.JSONException;

import saucaca.JSON.JsonReader;
import saucaca.JSON.WServiceLib;
import saucaca.Object.AlbumObject;
import saucaca.Object.SearchObject;
import saucaca.Object.SingerObject;
import saucaca.Object.SongObject;
import saucaca.Util.CMD;
import saucaca.Util.TagName;
import saucaca.fragment.AlbumDetailFargment;
import saucaca.fragment.ArtistDetailFragment;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v4.widget.DrawerLayout;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lemon.kenhnhacvn.BaseEngine;
import com.lemon.kenhnhacvn.MainActivity;
import com.lemon.kenhnhacvn.R;

public class CustomActionbar extends RelativeLayout {
	private LayoutInflater layoutInflater;
	RelativeLayout mActionLayout;
	ImageView imgLogo, imgSearchicon, imgHomeicon;
	TextView txtMenutitle;
	AutoCompleteTextView completeTextView;
	Context context;
	GetSearch getSearch;
	boolean isSearch = false, isHome;
	ArrayAdapter<SearchObject> adapter;
	ArrayList<SongObject> listSong = null;
	ArrayList<AlbumObject> listALBUM = null;
	ArrayList<SongObject> listVIDEO = null;
	ArrayList<SingerObject> listSinger = null;
	int singerSize = 0;
	int songSize = 0;
	int albumSize = 0;
	int videoSize = 0;

	private float offset;
	private boolean flipped;
	private DrawerArrowDrawable drawerArrowDrawable;
	DrawerLayout drawer;

	DrawerLayout.SimpleDrawerListener drawerListener;

	public CustomActionbar(final Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;
		layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mActionLayout = (RelativeLayout) layoutInflater.inflate(R.layout.actionbar_menu, null);
		addView(mActionLayout);

		listSong = new ArrayList<SongObject>();
		listALBUM = new ArrayList<AlbumObject>();
		listVIDEO = new ArrayList<SongObject>();
		listSinger = new ArrayList<SingerObject>();

		imgLogo = (ImageView) mActionLayout.findViewById(R.id.home_imgLogo);
		imgHomeicon = (ImageView) mActionLayout.findViewById(R.id.menu_top_navigation);
		imgSearchicon = (ImageView) mActionLayout.findViewById(R.id.menu_top_search);
		imgSearchicon.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				isSearch = !isSearch;
				toggleSearchview();
			}
		});

		txtMenutitle = (TextView) mActionLayout.findViewById(R.id.menu_top_text_title);
		completeTextView = (AutoCompleteTextView) mActionLayout.findViewById(R.id.search_home);
		completeTextView.addTextChangedListener(new TextWatcher() {

			@SuppressWarnings("unused")
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if (s.length() > 1) {
					if (getSearch == null) {
						getSearch = new GetSearch();
						getSearch.execute(s.toString());
					} else {
						if (getSearch.getStatus() == AsyncTask.Status.RUNNING) {
							getSearch.cancel(true);
							getSearch = new GetSearch();
							getSearch.execute(s.toString());
						} else {
							getSearch = new GetSearch();
							getSearch.execute(s.toString());
						}
					}
					isSearch = !isSearch;
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});
		completeTextView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
				if (imm != null) {
					if (hasFocus) {
						imm.showSoftInput(completeTextView, InputMethodManager.SHOW_IMPLICIT);
					} else
						imm.hideSoftInputFromWindow(completeTextView.getWindowToken(), 0);
				}

			}
		});
		completeTextView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				completeTextView.setText("");
				TagName.showLogError("Search", "index: " + position);
				if (position <= singerSize - 1) {
					((MainActivity) context).switchContent(ArtistDetailFragment.class.getName(), listSinger.get(position));
				} else if (position <= singerSize - 1 + albumSize) {
					((MainActivity) context).switchContent(AlbumDetailFargment.class.getName(), listALBUM.get(position - singerSize));
				} else if (position <= singerSize - 1 + albumSize + videoSize) {
					BaseEngine.setVideoclick(context, listVIDEO.get(position - singerSize - albumSize));
				} else {
					new songDetailsServices().execute(listSong.get(position - singerSize - albumSize - videoSize).getSONG_ID());
				}
				toggleSearchview();
				isSearch = true;
			}
		});
	}

	class songDetailsServices extends AsyncTask<String, String, String> {
		@Override
		protected String doInBackground(String... params) {
			String str = WServiceLib.idDetais(CMD.CMD_SONG_DETAIL, params[0]);
			return str;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (result != null)
				try {
					ArrayList<SongObject> listsongs = JsonReader.readSongdetail(result);
					if (listsongs != null && listsongs.size() > 0) {
						SongObject songObject = listsongs.get(0);
						try {
							((MainActivity) context).mPlaylistMgr.add(songObject);
							((MainActivity) context).play(((MainActivity) context).mPlaylistMgr.getArrayList().size() - 1);
						} catch (Exception e) {
							ArrayList<SongObject> lists = new ArrayList<SongObject>();
							lists.add(songObject);
							((MainActivity) context).SendPlaylistAndplay(lists, 0);
						}
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
		}
	}

	public void toggleSearchview() {
		if (isSearch) {
			imgLogo.setVisibility(View.GONE);
			txtMenutitle.setVisibility(View.GONE);
			completeTextView.setVisibility(View.VISIBLE);
			completeTextView.requestFocus();
			imgSearchicon.setImageResource(R.drawable.ic_action_remove);
		} else {
			if (isHome) {
				imgLogo.setVisibility(View.VISIBLE);
			} else
				txtMenutitle.setVisibility(View.VISIBLE);
			completeTextView.setVisibility(View.GONE);
			completeTextView.setText("");
			imgSearchicon.setImageResource(R.drawable.search_icon);
		}
	}

	public void setTitle(String title) {
		txtMenutitle.setText(title);
	}

	public void setMenu(CharSequence title, boolean isHome, boolean isMenu) {
		this.isHome = isHome;
		txtMenutitle.setText(title);
		setActionbar(isHome, isMenu);
		isSearch = false;
		toggleSearchview();
		// TagName.showLogError("setMenu",
		// "title: "+txtMenutitle.getText().toString()+"\nisHome: "+isHome+"\nisMenu: "+isMenu);
	}

	public void setDrawerArrowDrawable(DrawerLayout drawer, DrawerArrowDrawable ArrowDrawable) {
		this.drawerArrowDrawable = ArrowDrawable;
		this.drawer = drawer;
		imgHomeicon.setImageDrawable(drawerArrowDrawable);
		drawerListener = new DrawerLayout.SimpleDrawerListener() {
			@Override
			public void onDrawerSlide(View drawerView, float slideOffset) {
				offset = slideOffset;

				// Sometimes slideOffset ends up so close to but not quite 1 or
				// 0.
				if (slideOffset >= .995) {
					flipped = true;
					drawerArrowDrawable.setFlip(flipped);
				} else if (slideOffset <= .005) {
					flipped = false;
					drawerArrowDrawable.setFlip(flipped);
				}

				drawerArrowDrawable.setParameter(offset);
			}
		};
	}

	public void setMenu(int resid, boolean isHome, boolean isMenu) {
		this.isHome = isHome;
		txtMenutitle.setText(resid);
		setActionbar(isHome, isMenu);
		isSearch = false;
		toggleSearchview();
		// TagName.showLogError("setMenu",
		// "title: "+txtMenutitle.getText().toString()+"\nisHome: "+isHome+"\nisMenu: "+isMenu);
	}

	private void setActionbar(boolean isHome, boolean isMenu) {
		if (isHome) {
			imgLogo.setVisibility(View.VISIBLE);
			txtMenutitle.setVisibility(View.GONE);
			// imgHomeicon.setImageResource(R.drawable.menu_left);
			if (drawerArrowDrawable.getParameter() > 0) {
				drawerArrowDrawable.setParameter(0);
			}
			if (drawerListener != null)
				drawer.setDrawerListener(drawerListener);
			imgHomeicon.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					((MainActivity) context).showMenu();
					if (isSearch) {
						isSearch = !isSearch;
						toggleSearchview();
					}
				}
			});
		} else {
			imgLogo.setVisibility(View.GONE);
			txtMenutitle.setVisibility(View.VISIBLE);
			if (isMenu) {
				// imgHomeicon.setImageResource(R.drawable.menu_left);
				if (drawerArrowDrawable.getParameter() > 0) {
					drawerArrowDrawable.setParameter(0);
				}
				if (drawerListener != null)
					drawer.setDrawerListener(drawerListener);
				imgHomeicon.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						((MainActivity) context).showMenu();
						if (isSearch) {
							isSearch = !isSearch;
							toggleSearchview();
						}
					}
				});
			} else {
				// imgHomeicon.setImageResource(R.drawable.back_icon_ht);
				drawerArrowDrawable.setParameter(1);
				// drawerArrowDrawable.setFlip(true);
				drawer.setDrawerListener(null);
				imgHomeicon.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						((MainActivity) context).showprevousFragment();
						if (isSearch) {
							isSearch = !isSearch;
							toggleSearchview();
						}
						if (drawerListener != null)
							drawer.setDrawerListener(drawerListener);
					}
				});
			}
		}
	}

	class GetSearch extends AsyncTask<String, String, String> {
		@Override
		protected String doInBackground(String... params) {
			String str = WServiceLib.search(params[0]);
			// BaseEngine.showLogformLongString(str);
			return str;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (result != null) {
				listSong.clear();
				listALBUM.clear();
				listVIDEO.clear();
				listSinger.clear();
				ArrayList<SongObject> listSongJson = null;
				ArrayList<AlbumObject> listALBUMJson = null;
				ArrayList<SongObject> listVIDEOJson = null;
				ArrayList<SingerObject> listSingerJson = null;
				try {
					listSongJson = JsonReader.searchSong(result);
					listALBUMJson = JsonReader.searchAlbum(result);
					listVIDEOJson = JsonReader.searchVideo(result);
					listSingerJson = JsonReader.searchSinger(result);
				} catch (JSONException e) {
					e.printStackTrace();
				}

				if (listSingerJson != null && listSingerJson.size() > 0) {
					singerSize = listSingerJson.size();
					for (int i = 0; i < singerSize; i++) {
						listSinger.add(listSingerJson.get(i));
					}
				} else
					singerSize = 0;
				if (listALBUMJson != null && listALBUMJson.size() > 0) {
					albumSize = listALBUMJson.size();
					for (int i = 0; i < albumSize; i++) {
						listALBUM.add(listALBUMJson.get(i));
					}
				} else
					albumSize = 0;
				if (listVIDEOJson != null && listVIDEOJson.size() > 0) {
					videoSize = listVIDEOJson.size();
					for (int i = 0; i < videoSize; i++) {
						listVIDEO.add(listVIDEOJson.get(i));
					}
				} else
					videoSize = 0;
				if (listSongJson != null && listSongJson.size() > 0) {
					songSize = listSongJson.size();
					for (int i = 0; i < songSize; i++) {
						listSong.add(listSongJson.get(i));
					}
				} else
					songSize = 0;

				SearchObject[] people = new SearchObject[singerSize + albumSize + videoSize + songSize];
				for (int i = 0; i < singerSize; i++) {
					people[i] = new SearchObject(R.drawable.bl_avatar1, listSinger.get(i).getTXNAME());
				}
				for (int i = 0; i < albumSize; i++) {
					people[i + singerSize] = new SearchObject(R.drawable.cn_album, listALBUM.get(i).getTXNAME()+" - "+listALBUM.get(i).getNAME_SINGERS());
				}
				for (int i = 0; i < videoSize; i++) {
					people[i + singerSize + albumSize] = new SearchObject(R.drawable.cn_video, listVIDEO.get(i).getTXNAME()+" - "+listVIDEO.get(i).getNAME_SINGERS());
				}
				for (int i = 0; i < songSize; i++) {
					people[i + singerSize + albumSize + videoSize] = new SearchObject(R.drawable.cn_baihat, listSong.get(i).getTXNAME()+" - "+listSong.get(i).getNAME_SINGERS());
				}
				adapter = new FilteredArrayAdapter<SearchObject>(context, R.layout.item_search, people) {
					@Override
					public View getView(int position, View convertView, ViewGroup parent) {
						if (convertView == null) {

							LayoutInflater l = (LayoutInflater) getContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
							convertView = (View) l.inflate(R.layout.item_search, parent, false);
						}
						SearchObject p = getItem(position);
						if (p != null) {
							ImageView imageView = (ImageView) convertView.findViewById(R.id.imageView);
							imageView.setImageResource(p.avatar);
							((TextView) convertView.findViewById(R.id.textView)).setText(p.Name);
						}
						return convertView;
					}

					@SuppressLint("DefaultLocale")
					@Override
					protected boolean keepObject(SearchObject obj, String mask) {
						mask = mask.toLowerCase();
						return obj.Name.toLowerCase().startsWith(mask);
					}
				};
				completeTextView.setAdapter(adapter);
				completeTextView.showDropDown();
				isSearch = !isSearch;
			}
		}
	}
}
